import React, { useState, useEffect } from 'react';
import { Animated, TextInput, Dimensions, FlatList, StyleSheet, TouchableOpacity, Text, Button, View, Image, ImageBackground, ScrollView, ToastAndroid } from 'react-native';
import { EvilIcons } from '@expo/vector-icons';
import axios from '../api/axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useAuth, baseURL } from '../context/AuthProvider';
import moment from 'moment';
import Swiper from 'react-native-swiper';
import StickyHeader from '../component/News/StickyHeader'
import { useFocusEffect } from '@react-navigation/native';

const Btn = ({ children, style, color, ...rest }) => {
    return (
        <TouchableOpacity {...rest} style={
            {
                justifyContent: 'center',
                alignItems: 'center',
                ...style
            }
        }>
            <Text style={{ color: color ? color : '#fff' }}>{children}</Text>
        </TouchableOpacity>
    )
}
const { width, height } = Dimensions.get('window');

const News = ({ navigation }) => {
    const [list, setList] = useState([]);
    const [selectTab, setSelectTab] = useState("1");
    const [scrollY, setScrollY] = useState(new Animated.Value(0));
    const [headHeight, setHeadHeight] = useState(-1);
    const [imgs, setImgs] = useState([
        require('../../images/news/第一天.png'),
        require('../../images/news/第一天.png'),
        require('../../images/news/第一天.png'),
        require('../../images/news/第一天.png'),
        require('../../images/news/第一天.png')
    ])
    const [content, setContent] = useState("");
    const tagsData = [
        { label: '新手必看', id: '1', },
        { label: '防治病虫害', id: '2', },
        { label: '修枝剪叶', id: '3', },
        { label: '花卉养护', id: '4', },
        { label: '全部推荐', id: '', },
    ];
    const selectPlant = () => {
        axios.post('/guide/selectplant', {
            cropname: content
        }).then(res => {
            console.log(res);
            if (res.code == 200) {
                navigation.navigate('plantImage', {
                    images: res.data,
                    imgs: res.imgs
                });
                setContent('');
            }
            if (res.code == 500) {
                ToastAndroid.show('关键字错误', 2000)
            }
        })
    }
    const toMessage = (item) => {
        navigation.navigate('message', {
            item: item
        });
        axios.post('/guide/addread', {
            guideid: item.guideid
        }).then(res => {
            console.log(res);
        })
    }
    useEffect(() => {
        axios.get('/guide/get').then(res => {
            if (res.code == 200) {
                console.log(res.data[0].coverimgbig);
                setImgs(res.data)
            }
        })
    }, [])
    useEffect(() => {
        axios.post('/news/main', {
            newsType: selectTab
        }).then(res => {
            // console.log(res);
            if (res.code == 200) {
                setList(res.data);
            }
        })
    }, [selectTab])
    useEffect(() => {
        axios.get('/guide/get').then(res => {
            console.log(res);
            if (res.code == 200) {
                setImgs(res.data);
            }
        });
    }, [])
    // 返回刷新页面
    useFocusEffect(React.useCallback(() => {
        axios.post('/news/main', {
            newsType: selectTab
        }).then(res => {
            // console.log(res);
            if (res.code == 200) {
                setList(res.data);
            }
        })
    }, []))
    return (
        <Animated.ScrollView
            style={{ flex: 1, }}
            onScroll={
                Animated.event(
                    [{
                        nativeEvent: { contentOffset: { y: scrollY } } // 记录滑动距离
                    }],
                    { useNativeDriver: true }) // 使用原生动画驱动
            }
            scrollEventThrottle={1}
        >
            <View style={{ alignItems: 'center', backgroundColor: 'rgb(240,245,238)', width: '100%' }}>
                <View
                    style={{ backgroundColor: 'rgb(240,245,238)', }}
                    onLayout={(e) => {
                        let { height } = e.nativeEvent.layout;
                        setHeadHeight(height); // 给头部高度赋值
                    }}>
                    {/* 头部搜索栏 */}
                    <View style={styles.header}>
                        <Image style={styles.logo} source={require('../../images/news/logo.png')} />
                        <View style={styles.select}>
                            <EvilIcons name="search" size={24} color="black" style={{ paddingLeft: 12, marginRight: 3 }} />
                            <TextInput
                                style={{ width: '70%', lineHeight: height * 0.04 }}
                                placeholder='搜你想知道的植物百科'
                                value={content}
                                onChangeText={text => setContent(text)}
                            />
                            <Btn
                                style={content ? styles.sBtn : { display: 'none' }}
                                onPress={selectPlant}
                            >
                                <Text>搜 索</Text>
                            </Btn>
                        </View>
                    </View>
                    {/* 轮播图 */}
                    <View style={{ height: height * 0.23, alignItems: 'center', }}>
                        <Swiper autoplay={true} height={height * 0.23} showsPagination={true} dotColor="white"
                            activeDotColor='#9AD37A' horizontal={true}>
                            {
                                imgs.map((item, index) => {
                                    //cover: 等比例放大; center:不变; contain:不变; stretch:填充;
                                    return (
                                        <TouchableOpacity key={index}
                                            style={styles.swiperBox}
                                            onPress={() => toMessage(item)}>
                                            <Image
                                                style={styles.swiperImg}
                                                source={{ uri: baseURL + item.coverimgbig }}
                                            />
                                        </TouchableOpacity>
                                    )
                                })
                            }
                        </Swiper>
                    </View>
                </View>
                <StickyHeader
                    stickyHeaderY={headHeight} // 把头部高度传入
                    stickyScrollY={scrollY}  // 把滑动距离传入
                    style={{ backgroundColor: 'rgb(240,245,238)', width: width }}
                >
                    {/* 导航栏 */}
                    <View style={{
                        flexDirection: 'row',
                        marginBottom: '2.5%',
                        marginTop: '3%',
                    }}>
                        {
                            tagsData.map(item => (
                                <View style={{
                                    // borderWidth: 0.5, borderColor: '#9AD37A',
                                    height: 35, marginLeft: 15,
                                }}>
                                    <Btn
                                        key={item.id}
                                        onPress={() => {
                                            setSelectTab(item.id)
                                        }}
                                        style={selectTab == item.id ? {
                                            height: 35,
                                            borderBottomWidth: 3,
                                            borderColor: '#8DD962'
                                        } : { height: 35, }}
                                        color={selectTab == item.id ? '#000' : 'grey'}
                                    >
                                        <Text style={selectTab == item.id ? { fontSize: 17, fontWeight: 'bold' } : { fontSize: 15 }}>
                                            {item.label}
                                        </Text>
                                    </Btn>
                                </View>
                            ))
                        }
                    </View>
                </StickyHeader>
                <FlatList
                    data={list}
                    renderItem={({ item }) => {
                        // if (item.isrotograph == 0) {
                        return (
                            <TouchableOpacity activeOpacity={0.68} style={{ alignItems: 'center', marginBottom: '1.8%' }} key={item.guideid} onPress={() => toMessage(item)}>
                                <View style={{ width: '95%' }} key={item.guideid}>
                                    <View style={{ backgroundColor: '#fff', borderRadius: 10 }}>
                                        <Text style={styles.addTime}>{moment(item.date).format("YYYY-MM-DD HH:mm")}</Text>
                                        <View style={styles.outBox}>
                                            <View style={styles.textBox}>
                                                <Text style={styles.textTitle}>
                                                    {item.title}
                                                </Text>
                                                <Text style={{ color: '#c1c1c1', fontSize: 13.5 }}>
                                                    { } 阅读 {item.readnum}
                                                </Text>
                                            </View>
                                            <View style={{ width: '25%', alignItems: 'center', }}>
                                                <Image
                                                    style={styles.textImg}
                                                    source={{ uri: baseURL + item.coverimgsmall }}
                                                />
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        )
                        // }
                    }}
                />
            </View>
        </Animated.ScrollView>
    )
}

const styles = StyleSheet.create({
    header: {
        flexDirection: 'row',
        height: height * 0.08,
        backgroundColor: 'rgb(240,245,238)',
        // backgroundColor: 'rgb(235,243,243)',
        alignItems: 'center'
    },
    select: {
        flexDirection: 'row',
        alignItems: 'center',
        width: '75%',
        height: height * 0.04,
        borderRadius: 15,
        backgroundColor: '#fff',
        marginLeft: 13
    },
    logo: {
        width: '15%',
        height: height * 0.04,
        marginLeft: '2.7%'
    },
    swiperImg: {
        height: height * 0.23,
        width: '89%',
        borderRadius: 12,
        alignItems: 'center',
        // borderColor: '#9AD37A',
        // borderWidth: 1.5
    },
    swiperBox: {
        height: '100%',
        width: '100%',
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 12,
        marginLeft: 0
    },
    addTime: {
        height: 35,
        lineHeight: 35,
        marginLeft: width * 0.035,
        color: '#c1c1c1'
    },
    textBox: {
        width: '75%',
        justifyContent: 'center',
        paddingLeft: '3%',
        maxHeight: height * 0.14
    },
    textTitle: {
        lineHeight: 25,
        fontSize: 15,
        width: '92%',
        maxHeight: '60%',
        marginBottom: '2%'
    },
    textImg: {
        width: width * 0.17,
        height: width * 0.17,
        backgroundColor: '#fee'
    },
    outBox: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginBottom: '3%'
    },
    sBtn: {
        height: height * 0.032,
        width: '15%',
        backgroundColor: '#8DD962',
        borderRadius: 15,
    },
});

export default News;

